package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.NewsAutoScanConstants;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmUserMapper wmUserMapper;

    @Value("${file.oss.web-site}")
    private String webSite;
    /**
     * 分页查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //参数检查
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //条件封装
        LambdaQueryWrapper<WmNews> wrapper=new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(dto.getKeyWord())){
            wrapper.like(WmNews::getTitle,dto.getKeyWord());
        }
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getBeginPubdate()!=null&& dto.getEndPubdate()!=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        //查询用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        wrapper.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> pageParam=new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(pageParam, wrapper);

        PageResponseResult result = new PageResponseResult(
                dto.getPage(),
                dto.getSize(),
                (int) pageResult.getTotal(),
                pageResult.getRecords()
        );
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @param isSubmit 是否提交  1提交    0草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1参数合法性
        if (dto==null|| StringUtils.isBlank(dto.getContent())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //文章布局自动则设置wmNews的type为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //处理dto参数 images集合转换成字符串
        wmNews.setImages(
                dto.getImages().toString()
                .replace("[","")
                .replace("]","")
                .replace(webSite,"")
                .replace(" ","")
        );
        saveWmNews(wmNews, isSubmit);

        /**
        3关联文章和素材关系表：
            解析图片内容
            关联文章内容中图片和素材
            关联文章封面图片和素材   ==封面可能是自动选择或者无图模式
        */
        List<Map> contentImages= JSON.parseArray(dto.getContent(),Map.class);
        List<String> materials = parseContentImages(contentImages);//解析前端传来context中的图片内容

        if (isSubmit==WmNews.Status.SUBMIT.getCode()&& materials.size()>0){
            saveRelativeInfoForContent(materials,wmNews.getId());
        }

        if (isSubmit==WmNews.Status.SUBMIT.getCode()){
            saveRelativeInfoForCover(dto,materials, wmNews);
        }

        //kafka发消息给后台审核文章
        HashMap<String, Integer> map = new HashMap<>();
        map.put("WmNewsId",wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,
                JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据文章id查询文章 wm-news表
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(id);

        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

//        wmNews.setImages(webSite+wmNews.getImages());//设置正确的文件路径  setHost才正确
        ResponseResult result=ResponseResult.okResult(wmNews);
        result.setHost(webSite);

        return result;
    }

    /**
     * 删除文章 wm-news表==wmNewsMaterial表
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,
                    "文章id必须存在");
        }

        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                    "文章不存在");
        }

        //status=9已发布，enable=1已提交
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
        && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                    "已发布和已提交的文章不能删除");
        }

        //去素材库删除文章关系
        wmNewsMaterialMapper.delete(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId())
        );
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(
                Wrappers.<WmNews>lambdaQuery()
                        .le(WmNews::getPublishTime, new Date())
                        .in(WmNews::getStatus, 4, 8).select(WmNews::getId)
        );
        List<Integer> ids = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return ids;
    }

    /**
     * 文章上下架 wm-news表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST
            ,"文章不存在");
        }

        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                    "文章不是发布状态能上下架");
        }
        if (dto.getEnable()!=null && dto.getEnable()>-1 && dto.getEnable()<2){
            update(
              Wrappers.<WmNews>lambdaUpdate()
                      .eq(WmNews::getId,dto.getId())
                    .set(WmNews::getEnable,dto.getEnable())
            );
            //发消息给App端
            if (wmNews.getArticleId()!=null){
                Map<String, Object> map=new HashMap();
                map.put("enable",dto.getEnable());
                map.put("articleId",wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关联文章封面中的图片和素材
     * @param dto 前端用户选择封面信息数据
     * @param materials 从内容中解析的图片列表
     * @param wmNews 文章ID
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){//自动获取封面
            int materialSize = materials.size();
            if (materialSize>0 && materialSize<=2){//单图
                images=materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (materialSize>2){//多图
                images=materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {//无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null && images.size() > 0){
                wmNews.setImages(
                        images.toString()
                                .replace("[", "")
                                .replace("]", "")
                                .replace(webSite, "")
                                .replace(" ","")
                );
            }

            updateById(wmNews);
        }

        //保存封面图和素材关系
        if (images!=null && images.size()>0){
            saveRelativeInfoForImage(images, wmNews.getId());
        }
    }

    /**
     *  保存封面图和素材关系
     * @param images
     * @param newsId
     */
    private void saveRelativeInfoForImage(List<String> images, Integer newsId) {
        images = images.stream()
                .map(
                        x->x.replace(webSite,"")
                        .replace(" ","")
                ).collect(Collectors.toList());

        saveRelativeInfo(images, newsId, WemediaConstants.WM_IMAGE_REFERENCE);
    }

    /**
     *关联文章内容中的图片和素材
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存素材和文章关系
     * @param materials 素材列表
     * @param newsId 文章ID
     * @param type 类型 0：内容中素材  1：封面素材
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materials)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );

        List<Integer> materialIds = new ArrayList<>();
        if (dbMaterials==null || dbMaterials.size()==0){
            CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
        }

        //草稿中的图片列表大于等于数据素材
        Map<String, Integer> matreialMap=dbMaterials.stream()
                .collect(Collectors.toMap(
                        WmMaterial::getUrl,WmMaterial::getId
                ));

        for (String material : materials) {
            Integer id = matreialMap.get(material);
            if (id==null){
                CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }
            materialIds.add(id);
        }

        wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
    }

    /**
     * 解析图片内容
     * @param contentImages
     * @return
     */
    private List<String> parseContentImages(List<Map> contentImages) {
        List<String> materials = new ArrayList<>();
        for (Map contentImage : contentImages) {
            if (contentImage.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)){
                String imageUrl= (String) contentImage.get("value");
                imageUrl=imageUrl.replace(webSite,"");
                materials.add(imageUrl);
            }
        }
        return materials;
    }

    /**
     *保存或修改文章
     * @param wmNews 前端传递文章对象
     * @param isSubmit
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setEnable((short) 1);//上架
        //带id时修改，不带id时保存
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            //先删除再更新
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getId,wmNews.getId())
            );
            updateById(wmNews);
        }
    }

    /**
     * 查询文章列表(包含作者)
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();
        Integer curPage = dto.getPage();//当前页
        dto.setPage((curPage-1)*dto.getSize());//起始索引

        if (StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> wmNewsVos = baseMapper.findListAndPage(dto);//自媒体文章列表
        Integer count = baseMapper.findListCount(dto);//总条数

        //结果封装
        ResponseResult result = new PageResponseResult(curPage, dto.getSize(), count, wmNewsVos);
        result.setHost(webSite);//记得封装图片前缀

        return result;
    }

    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //封装文章  并执行修改
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }

        updateById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {

        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser=null;
        if (wmNews.getUserId()!=null){
            wmUser= wmUserMapper.selectById(wmNews.getUserId());

        }

        WmNewsVo wmNewsVo=new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if (wmUser!=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(webSite);//记得图片前缀

        return result;
    }
}
